package znet

import (
	"errors"
	"fmt"
	"io"
	"net"
	"sync"
	"zinx/utils"
	"zinx/ziface"
)

type Connection struct {
	// 当前连接所属的Server
	TcpServer ziface.IServer

	// 当前连接的socket TCP 套接字
	Conn *net.TCPConn
	// 连接的ID
	ConnID uint32
	// 当前的连接状态
	isClosed bool

	// 告知当前连接已经退出/停止的 channel ()
	ExitChan chan bool

	// 无缓冲的管道，用于读、写Goroutine之间的消息通信
	msgChan chan []byte

	// 该链接处理的方法
	MsgHandler ziface.IMsgHandler

	// 连接属性的集合
	property map[string]interface{}
	// 保护连接属性的锁
	propertyLock sync.RWMutex
}

func NewConnect(tcpServer ziface.IServer, conn *net.TCPConn, connId uint32, msgHandler ziface.IMsgHandler) *Connection {
	c := &Connection{
		TcpServer:  tcpServer,
		Conn:       conn,
		ConnID:     connId,
		isClosed:   false,
		ExitChan:   make(chan bool, 1),
		msgChan:    make(chan []byte),
		MsgHandler: msgHandler,
		property:   make(map[string]interface{}),
	}

	c.TcpServer.GetConnManger().ADD(c)

	return c
}

// StartReader 连接的读业务方法
func (c *Connection) StartReader() {
	fmt.Println("[Reader Goroutine is running...]")
	defer fmt.Println("connID = ", c.ConnID, " Reader is exit, remote addr is ", c.RemoteAddr().String())
	defer c.Stop()

	for {
		// 创建一个拆包解包的对象
		dp := NewDataPack()

		// 读取客户端的Msg Head 二进制流
		headData := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(c.GetTCPConnection(), headData); err != nil {
			fmt.Println("read msg head error :", err)
			break
		}

		// 拆包，得到msg的ID 和 DataLen 放在msg消失中
		msg, err := dp.Unpack(headData)
		if err != nil {
			fmt.Println("unpack error: ", err)
			break
		}
		// 再根据dataLen 再次读取Data， 放在msg.Data中
		data := make([]byte, msg.GetMsgLen())
		if _, err := io.ReadFull(c.GetTCPConnection(), data); err != nil {
			fmt.Println("read msg data error :", err)
			break
		}
		msg.SetData(data)

		// 得到当前conn数据的Request请求数据
		req := Request{
			conn: c,
			msg:  msg,
		}

		if utils.GlobalObject.WorkerPoolSize > 0 {
			// 交给消息队列处理
			c.MsgHandler.SendMsgToTaskQueue(&req)
		} else {
			// 从路由中找到注册绑定的Conn对应的router调用
			go c.MsgHandler.DoMsgHandler(&req)
		}
	}
}

// StartWrite 写消息
func (c *Connection) StartWrite() {
	fmt.Println("[Writer Goroutine is running...]")
	defer fmt.Println(c.RemoteAddr().String(), " conn Writer exit!")

	// 不断的阻塞等待channel的消息，写给客户端
	for {
		select {
		case data := <-c.msgChan:
			if _, err := c.Conn.Write(data); err != nil {
				fmt.Println("Send data error: ", err)
				return
			}
		case <-c.ExitChan:
			// Reader退出后，Writer也要退出
			return
		}
	}

}

// Start 启动连接, 让当前的连接开始工作
func (c *Connection) Start() {
	fmt.Println("Conn Start()... ConnId = ", c.ConnID)

	// 启动当前连接的读数据的业务
	go c.StartReader()
	// 启动从当前连接写数据的业务
	go c.StartWrite()

	c.TcpServer.CallOnConnStart(c)
}

// Stop 停止连接, 结束当前连接的工作
func (c *Connection) Stop() {
	fmt.Println("Conn Stop()... ConnID = ", c.ConnID)

	// 如果当前连接已经关闭
	if c.isClosed {
		return
	}

	// 调用开发者注册的 销毁连接之前 需要执行的业务Hook函数
	c.TcpServer.CallOnConnStop(c)

	// 关闭socket连接
	if err := c.Conn.Close(); err != nil {
		return
	}

	// 告知Writer关闭
	c.ExitChan <- true

	// 将当前连接从ConnManger中删除掉
	c.TcpServer.GetConnManger().Remove(c)

	// 回收资源
	close(c.ExitChan)
	close(c.msgChan)
}

// GetTCPConnection 获取当前连接绑定的socket conn
func (c *Connection) GetTCPConnection() *net.TCPConn {
	return c.Conn
}

// GetConnId 获取当前连接模块的连接ID
func (c *Connection) GetConnId() uint32 {
	return c.ConnID
}

// RemoteAddr 获取远程客户端的TCP状态 IP port
func (c *Connection) RemoteAddr() net.Addr {
	return c.Conn.RemoteAddr()
}

// SendMsg 提供一个SendMsg方法 将我们要发送给客户端的数据先进行封包，在发送
func (c *Connection) SendMsg(msgId uint32, data []byte) error {
	if c.isClosed {
		return errors.New("connection closed when send msg")
	}

	dp := NewDataPack()

	binaryMsg, err := dp.Pack(NewMessage(msgId, data))
	if err != nil {
		fmt.Println("Pack error msg id = ", msgId)
		return errors.New("pack error msg")
	}

	// 将数据发送给客户端
	c.msgChan <- binaryMsg
	return nil
}

// SetProperty 设置连接属性
func (c *Connection) SetProperty(key string, value interface{}) {
	c.propertyLock.Lock()
	defer c.propertyLock.Unlock()
	c.property[key] = value
}

// GetProperty 获取连接属性
func (c *Connection) GetProperty(key string) (interface{}, error) {
	c.propertyLock.RLock()
	defer c.propertyLock.RUnlock()

	if value, ok := c.property[key]; ok {
		return value, nil
	}
	return nil, errors.New("no property found")
}

// RemoveProperty 移除连接属性
func (c *Connection) RemoveProperty(key string) {
	c.propertyLock.Lock()
	defer c.propertyLock.Unlock()

	delete(c.property, key)
}
